<template>
  <BasicModal width="800px" @register="register"
              title="编辑" @ok.stop="handleSubmit">
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicModal>
</template>
<script setup>
import { BasicModal, useModal } from "@/components/Modal";
import { BasicForm, useForm } from "@/components/Form";
import { defHttp } from "@/utils/http/axios";
import { nextTick } from "vue";

defineOptions({ name: "UnitModal" });
const [register, { closeModal, openModal, setModalProps }] = useModal();
const [registerForm, {
  getFieldsValue,
  resetFields,
  validateFields,
  setFieldsValue,
  validate
}] = useForm({
  labelWidth: 150,
  schemas: [
    {
      field: "id",
      label: "id",
      component: "Input",
      show: false
    },
    {
      field: "unitCode",
      label: "单位编码",
      component: "Input",
      required: true
    },
    {
      field: "unitName",
      label: "单位名称",
      component: "Input",
      required: true
    },
    {
      field: "unitFullName",
      label: "单位全称",
      component: "Input",
      required: true
    },
    {
      field: "accountingType",
      label: "账簿分类",
      component: "Input"
    },
    {
      field: "accountingCode",
      label: "账簿编码",
      component: "Input",
      required: true
    },
    {
      field: "accountingKey",
      label: "账簿主键",
      component: "Input",
      required: true
    },
    {
      field: "accountingGroup",
      label: "财务组织",
      component: "Input"
    },
    {
      field: "division",
      label: "行政区划",
      component: "Input"
    }
  ],
  showActionButtonGroup: false
});
const Api = {
  add: "/cwqs/cwqsUnit/add",
  edit: "/cwqs/cwqsUnit/edit"
};
const emits = defineEmits(['ok'])

function handleSubmit() {
  validate().then(data => {
    defHttp.post({ url: data.id ? Api.edit : Api.add, data }).then(data => {
      closeModal();
      emits('ok')
    });
  });
}

function setData(id) {
  openModal();
  nextTick(() => {
    resetFields();
  })
  if (id) {
    setModalProps({confirmLoading: true})
    defHttp.get({url: '/cwqs/cwqsUnit/queryById', params: {id}}, {joinParamsToUrl: true}).then(data => {
      nextTick(() => {
        setFieldsValue(data);
      })
      setModalProps({confirmLoading: false})
    }).catch(e => {
      setModalProps({confirmLoading: false})
    })
  }
}

defineExpose({
  setData
});
</script>
